package com.kaige.asktaoplugin60.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * 心跳检测处理器
 */
@Slf4j
public class HeartbeatHandler extends IdleStateHandler {
    
    private static final ByteBuf HEARTBEAT_BUF = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer(new byte[0]));
    
    public HeartbeatHandler(int readerIdleTimeSeconds, int writerIdleTimeSeconds, int allIdleTimeSeconds) {
        super(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds);
    }
    
    @Override
    protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
        log.info("检测到空闲连接，事件类型: {}", evt.state());
        
        switch (evt.state()) {
            case READER_IDLE:
                log.warn("读空闲，关闭连接: {}", ctx.channel().remoteAddress());
                ctx.close();
                break;
            case WRITER_IDLE:
                log.info("写空闲，发送心跳包: {}", ctx.channel().remoteAddress());
                ctx.writeAndFlush(HEARTBEAT_BUF.duplicate());
                break;
        }
        
        super.channelIdle(ctx, evt);
    }
}